package com.allwees.core.common.util.excel;

import com.alibaba.excel.EasyExcel;
import com.allwees.core.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author linqiu
 * @create 2019/11/1 12:00
 */
@Slf4j
public class ExcelUtil {

    /**
     * 导出 Excel ：一个 sheet，带表头
     *
     * @param response  HttpServletResponse
     * @param beans      数据 list，每个元素为一个 BaseRowModel
     * @param fileName  导出的文件名
     * @param sheetName 导入文件的 sheet 名
     * @param type    映射实体类，Excel 模型
     */
	public static void writeExcel(HttpServletResponse response, List<?> beans, String fileName, String sheetName,
			Class<?> type) {
		Assert.notEmpty(beans, "data cannot empty");
        try {
            initResponse(response, fileName);
            EasyExcel
                    .write(response.getOutputStream(), type)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet(sheetName)
                    .doWrite(beans);
        } catch (Exception e) {
            throw new BaseException("导出出错~");
        }
    }

    private static void initResponse(HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.ms-excel");
        String encoding = StandardCharsets.UTF_8.name();
        response.setCharacterEncoding(encoding);
        fileName = URLEncoder.encode(fileName, encoding);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    }
}
